<?php
namespace app;

use Server\CoreBase\HttpInput;
use Server\CoreBase\Loader;
use Server\SwooleDistributedServer;
use WsdServer\WsdSwooleDistributedServer;

use WsdServer\Components\AMQPTaskSystem\WsdAMQPTaskProcess;

use Server\Components\Process\ProcessManager;

/**
 * Created by PhpStorm.
 * User: zhangjincheng
 * Date: 16-9-19
 * Time: 下午2:36
 *
 * Modify by hb on 2017-12-22: extends 由 SwooleDistributedServer 改为 WsdSwooleDistributedServer
 */
//class AppServer extends SwooleDistributedServer
class AppServer extends WsdSwooleDistributedServer
{

    /**
     * 可以在这里自定义Loader，但必须是ILoader接口
     * AppServer constructor.
     */
    public function __construct()
    {
        $this->setLoader(new Loader());
        parent::__construct();
    }

    /**
     * 开服初始化(支持协程)
     * @return mixed
     */
    public function onOpenServiceInitialization()
    {
        yield parent::onOpenServiceInitialization();
    }

    /**
     * 这里可以进行额外的异步连接池，比如另一组redis/mysql连接
     * @param $workerId
     * @return array
     */
    public function initAsynPools($workerId)
    {
        parent::initAsynPools($workerId);

    }

    /**
     * 用户进程
     */
    public function startProcess()
    {
        parent::startProcess();

        // Add by hb on 2017-12-11: 初始化启动MQ消费进程
        if ($this->config->get('amqp.consume.enable', false)) {
            $consumes = $this->config->get('amqp.consumes', "");
            //var_dump($consumes);
            $j = 0;
            foreach ($consumes as $consume){
                for ($i=1; $i<=$consume["concurrent"]; $i++){
                    $process = ProcessManager::getInstance()->addProcess(WsdAMQPTaskProcess::class,true,$j);
                    $process->setConsumeQueue($consume["queue"]);
                    $process->setHandlerClass($consume["class"]);
                    //echo "=== ampq_consume_process[worker_id=".$process->worker_id.", ".$consume["queue"].
                    //     "(".$i."/".$consume['concurrent'].")] ===\n";
                    $j++;
                }
            }
        }
    }

    /**
     * 可以在这验证WebSocket连接,return true代表可以握手，false代表拒绝
     * @param HttpInput $httpInput
     * @return bool
     */
    public function onWebSocketHandCheck(HttpInput $httpInput)
    {
        return true;
    }

    /**
     * @return string
     */
    public function getCloseMethodName()
    {
        return 'onClose';
    }

    /**
     * @return string
     */
    public function getEventControllerName()
    {
        return 'AppController';
    }

    /**
     * @return string
     */
    public function getConnectMethodName()
    {
        return 'onConnect';
    }
}